package com.imarad.bio.socket.core;

import com.imarad.bio.socket.common.ClientPacket;
import com.imarad.bio.socket.common.Constants;

import java.io.IOException;
import java.net.Socket;

/**
 * Copyright2017-2017  AMBITION.All Rights Reserved
 *
 * Comments：
 *
 * @author huh
 *
 *         Time: 2018/2/1
 *
 *         Modified By:
 *         Modified Date:
 *         Why & What is modified:
 * @version 1.0.0
 */
class ReadSocketClient implements Runnable, SocketClient {

    private Socket mSocket;

    private boolean isRun;

    private ConnectedCallback mConnectedCallback;

    public ReadSocketClient(Socket socket, ConnectedCallback connectedCallback) {
        mSocket = socket;
        mConnectedCallback = connectedCallback;
    }

    @Override
    public void run() {
        Thread.currentThread().setName("ReadSocketClient");
        isRun = true;
        while (isRun) {
            mConnectedCallback.receiveMessage(read());
        }
    }

    @Override
    public void stop() {
        isRun = false;
    }

    @Override
    public void send(ClientPacket clientPacket) {
        throw new SocketClientException("读取数据线程不负责发送数据到服务器");
    }


    /**
     * 发送数据到服务端
     */
    @Override
    public ClientPacket read() {
        ClientPacket packet = null;
        // 获取Socket的OutputStream对象用于发送数据
        try {
            // read packet header (17)
            byte[] data = new byte[Constants.PACKET_HEADER_LEN];
            int eof = mSocket.getInputStream().read(data, 0, data.length);
            if (eof < -1) {
                return null;
            }
            packet = new ClientPacket(data);
            data = new byte[packet.getPacketLen()];
            eof = mSocket.getInputStream().read(data, 0, data.length);
            if (eof < -1) {
                return packet;
            }
            packet.setData(data);
        } catch (IOException e) {
            isRun = false;
            e.printStackTrace();
        } finally {
            return packet;
        }
    }
}
